# coding: utf-8

#在get_tickets_info的基础上站点名变量化，不用直接输入大写代号
#第一次请求时，会导入数据到txt中

import os
import os.path
import time
import sys,traceback
from src.main.station.generate_station_msg import load_station_into_txt,get_key,get_name,generate_query_body,generate_preform_msg,validate_input_msg

def request_tickets_data(from_station, to_station, date,stationfile_content,num_retries=10,request_num=1):
    try:
        cli(from_station, to_station, date, stationfile_content)
    except :
        t, v, tb = sys.exc_info()
        #traceback.print_tb(tb)
        html = None

        if num_retries > 0:
            print("第"+str(request_num)+"次请求失败")
            time.sleep(2)
            request_num+=1
            return request_tickets_data(from_station, to_station, date,stationfile_content, num_retries-1,request_num)
        else:
            print("没有请求到数据，请稍后再试")


def initial():
    dir_base = os.path.abspath('.')
    dir_relate="middle_file"
    dir_full_path = os.path.join(dir_base, dir_relate)
    filename=os.path.join(dir_full_path,"station_msg_info_"+time.strftime("%Y%m%d", time.localtime())+".txt")

    print('站点信息文件路径为：'+filename)
    if(os.path.exists(filename)):
       print("站点信息文件已经存在")
    else:
        load_station_into_txt(filename)

    #print(get_key('北京北'))
    stationfile_opener = open(filename, 'r', encoding="utf-8")
    # 发送get请求，不判断证书
    # 　使用正则表达式提取所有的站点：汉字和大写代号
    stationfile_content=stationfile_opener.read()
    stationfile_opener.close()

    return stationfile_content

def cli(from_station,to_station,date,stationfile_content):
    request_data_body=generate_query_body(from_station,to_station,date,stationfile_content)
    generate_preform_msg(request_data_body,stationfile_content)



if __name__ == '__main__':
    from_station = '上海'
    to_station = '天水'
    date = '2018-02-09'
    start_time = time.time()
    stationfile_content = initial()
    if(validate_input_msg(from_station, to_station, stationfile_content)):
        request_tickets_data(from_station, to_station, date, stationfile_content)
        print('此次查询一共耗时：' + str(time.time() - start_time) + 's')
